package com.chagee.channel.server.event.service.impl;

import cn.hutool.json.JSONUtil;

import com.chagee.channel.api.bo.oss.FileNameListReq;
import com.chagee.channel.api.bo.oss.NewFile;
import com.chagee.channel.server.event.service.CosService;

import javax.annotation.Resource;

import com.qcloud.cos.COS;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.mps.v20190612.MpsClient;
import com.tencentcloudapi.mps.v20190612.models.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.util.concurrent.ThreadPoolExecutor;

import static com.tencentcloudapi.common.profile.HttpProfile.REQ_HTTPS;

@Slf4j
@Service
public class CosServiceImpl implements CosService {

    @Value("${qcloud.cos.accessId}")
    private String ACCESS_KEY_ID;
    @Value("${qcloud.cos.accessSecret}")
    private String SECRET_ACCESS_KEY;
    @Value("${qcloud.cos.id}")
    private String QCCLOUD_ID;
    @Value("${qcloud.cos.bucket}")
    private String COS_BUCKET;
    @Value("${qcloud.cos.region}")
    private String COS_REGION;
    @Value("${qcloud.cos.prefix}")
    private String COS_DIR_PREFIX;
    @Value("${qcloud.cos.time:3}")
    private String COS_EXPIRE;
    @Resource(name = "cosSyncExecutor")
    private ThreadPoolExecutor threadPoolExecutor;

    @Value("${qcloud.mps.secretId}")
    private String MPS_KEY_ID;
    @Value("${qcloud.mps.secretKey}")
    private String MPS_ACCESS_KEY;

    @Resource
    private COSClient cosClient;

    @Override
    public String getMP4(String objectName) {
        try {
            // 配置阿里云 COS 访问凭证
            String accessKeyId = ACCESS_KEY_ID;
            String accessKeySecret = SECRET_ACCESS_KEY;
            String endpoint ="ap-nanjing.myqcloud.com"; // COS Endpoint
            ClientConfig clientConfig = new ClientConfig(new Region(COS_REGION));
            // 初始化 Cos 客户端
            COSCredentials cred = new BasicCOSCredentials(accessKeyId, accessKeySecret);
            COS cosClient=new COSClient(cred, clientConfig);
//
            String bucketName="bwda-1305015670";
            String mp4ObjectName = objectName.split("\\.")[0] + "_transcode_1270375.mp4";
            log.info("mp4:{}",mp4ObjectName);
            // 检查对象是否存在
            boolean exists = cosClient.doesObjectExist(bucketName, mp4ObjectName);
            if (exists) {
                log.info("mp4ObjectName " + objectName + "exists_in_bucket " + bucketName + ".");
                log.info("newurl:{}",mp4ObjectName);
                return mp4ObjectName;
            } else {
                log.info("Object " + mp4ObjectName + "does_not_exist_in_bucket " + bucketName + ".");
            }
        } catch (Exception e) {
            log.warn("Error: " + e.getMessage());
        }finally {
            // 关闭COSClient
            cosClient.shutdown();
        }
        return objectName;
    }


    @Override
    public int toMP4(FileNameListReq fileNamelist) {
        NewFile newFile=new NewFile();
        int count=0;
        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(MPS_KEY_ID, MPS_ACCESS_KEY);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("mps.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            MpsClient client = new MpsClient(cred, "", clientProfile);

            // 替换为你的转码模板 ID
            Long templateId = Long.valueOf(1270375);

            TranscodeTaskInput transcodeTaskInput=new TranscodeTaskInput();
            transcodeTaskInput.setDefinition(templateId);

            for (NewFile file : fileNamelist.getFiles()) {
                log.info("fileName:{}", file.getFileName());
                if (!file.getFileName().equals(this.getMP4(file.getFileName()))) {
                    log.info("this.getMP4(file.getFileName():{}", this.getMP4(file.getFileName()));
                    continue;
                }
                CosInputInfo cosInputInfo = new CosInputInfo();
                cosInputInfo.setBucket("bwda-1305015670");
                cosInputInfo.setObject(file.getFileName());// 替换为要处理的视频的 URL;
                cosInputInfo.setRegion(COS_REGION);
                // 实例化一个请求对象,每个接口都会对应一个request对象
                ProcessMediaRequest req = new ProcessMediaRequest();
                MediaInputInfo mediaInputInfo=new MediaInputInfo();
                mediaInputInfo.setType("COS");
                req.setInputInfo(mediaInputInfo);
                req.getInputInfo().setCosInputInfo(cosInputInfo);
                MediaProcessTaskInput mediaProcessTaskInput=new MediaProcessTaskInput();
                mediaProcessTaskInput.setTranscodeTaskSet(new TranscodeTaskInput[]{transcodeTaskInput});
                req.setMediaProcessTask(mediaProcessTaskInput);
                log.info("ProcessMediaRequest:{}", JSONUtil.toJsonStr(req));
                String outputObject = file.getFileName().split("\\.")[0] + "_transcode_1270375.mp4";
                log.info("outputObject:{}",outputObject);
                // 返回的resp是一个ProcessMediaResponse的实例，与请求对象对应
                log.info("开始执行转码");
                ProcessMediaResponse resp = client.ProcessMedia(req);
                log.info("ProcessMediaResponse:{}",AbstractModel.toJsonString(resp));
                // 输出json格式的字符串回包
                log.info("JobId: " + resp.getTaskId());
                newFile.setJobId( resp.getTaskId());
                newFile.setNewFileName(outputObject);
                if(newFile.getJobId()!=null){
                    count++;
                }
            }
        } catch (TencentCloudSDKException e) {
            log.warn("发起转换失败原因:",e);
        }

        return count;
    }

//    @Override
//    public NewFile toMP4(FileNameListReq fileNamelist) {
//        // 替换为你的腾讯云 API 密钥信息
//        String secretId = ACCESS_KEY_ID;
//        String secretKey = SECRET_ACCESS_KEY;
//
//        // 替换为你的转码模板 ID
//        String templateId = "your_transcode_template_id";
//
//
//
//
//        try {
//            // 初始化云点播客户端
//            Credential cred = new Credential(secretId, secretKey);
//
//            // 实例化客户端配置
//            HttpProfile httpProfile = new HttpProfile();
//            httpProfile.setEndpoint("vod.tencentcloudapi.com");
//
//            ClientProfile clientProfile = new ClientProfile();
//            clientProfile.setHttpProfile(httpProfile);
//
//            VodClient client = new VodClient(cred, "ap-guangzhou"); // 指定地域，例如这里是广州
//
//            // 构造请求
//            ProcessMediaByUrlRequest req = new ProcessMediaByUrlRequest();
//            req.getInputInfo().setUrl("your_input_video_url"); // 替换为要处理的视频的 URL;
//            req.getOutputInfo().setBucket("");
//            req.getOutputInfo().setDir("");
//            req.getOutputInfo().setRegion("");
//            req.getOutputInfo().set("","");
//
//
//
//
//            // 提交转码任务
//            ProcessMediaByUrlResponse resp = client.ProcessMediaByUrl(req);
//
//            // 输出转码任务的任务 ID
//            System.out.println("Transcode task ID: " + resp.getTaskId());
//        } catch (TencentCloudSDKException e) {
//            System.out.println("Error: " + e.toString());
//        }
//        return null;
//    }
}
